﻿using NewAndong.Comm;
using NewAndong.Enum;
using NewAndong.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace NewAndong
{
    public class PublicHelper
    {
        /// <summary>
        /// PING IP地址
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool PingIp(string ip)
        {
            bool result = false;
            try
            {
                Ping pingSend = new Ping();
                PingReply reply = pingSend.Send(ip, 2000);
                if (reply.Status == IPStatus.Success)
                    result = true;
            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 字节数组转二进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ByteToStr(byte[] bytes)
        {
            string strResult = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                string strTemp = Convert.ToString(bytes[i], 2);
                strTemp = strTemp.Insert(0, new string('0', 8 - strTemp.Length));
                //倒叙
                strTemp = ReverseD(strTemp);
                strResult += strTemp;
            }
            return strResult;
        }

        /// <summary>
        /// 二进制字符串转字节数组
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static byte[] StrToByte(string str)
        {
            byte[] bytes = new byte[str.Length / 8];
            for (int i = 0; i < bytes.Length; i++)
            {
                bytes[i] = Convert.ToByte(str.Substring(i * 8, 8), 2);
            }
            return bytes;
        }

        /// <summary>
        /// 字符串倒叙
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string ReverseD(string text)
        {
            return new string(text.ToCharArray().Reverse().ToArray());
        }


        public static byte[] ReadPlcDataTest(TriaModel plcTria)
        {
            byte[] result = null;
            var groupStr = new StringBuilder();
            //循环判断每一组数据
            for (uint i = plcTria.TriaAddress.Address; i < (plcTria.TriaAddress.Address + plcTria.AddressLength); i++)
            {
                try
                {
                    //根据组ID获取该组
                    var triaGroup = plcTria.TriaGroups.Where(s => s.GroupId == plcTria.TriaAddress.Identifier + i.ToString("X")).FirstOrDefault();
                    if (triaGroup == null)
                    {
                        continue;
                    }

                    var group = GolbalVariable.TriaGroupList.Where(s => s.GroupAddress == plcTria.TriaAddress.Identifier + i.ToString("X")).FirstOrDefault();
                    var items = GolbalVariable.TriaItemList.Where(s => s.GroupID == group.ID).ToList();
                    var oldvalue = "";
                    switch (triaGroup.GroupDataType)
                    {
                        case TriaDataType.Integer:
                            if (string.IsNullOrEmpty(triaGroup.GroupStrs))
                            {
                                if (group.SignalMark == "TS")
                                {
                                    triaGroup.GroupStrs = "0000000000000000";
                                }
                                else
                                    triaGroup.GroupStrs = "0000000000110000";
                            }
                            else
                            {
                                oldvalue = triaGroup.GroupStrs;
                                var oldstr = ReverseD(oldvalue);//先反转
                                triaGroup.GroupStrs = BinaryAddOne(oldstr);//先加1
                            }

                            groupStr.Append(triaGroup.GroupStrs);

                            triaGroup.GroupStrs = oldvalue;
                            break;
                        case TriaDataType.Booleans:
                            var oldGroupValue = triaGroup.GroupStrs;
                            if (string.IsNullOrEmpty(oldGroupValue))
                                oldGroupValue = "0000000000000000";
                            var newGroupValue = "";
                            for (int j = 0; j < 16; j++)
                            {
                                //将读到的二进制数转成单个0或1并更新到数据模型中
                                var oldboolvalue = int.Parse(oldGroupValue[j].ToString());
                                var strValue = (oldboolvalue == 0 ? 1 : 0).ToString();
                                newGroupValue += strValue;
                                triaGroup.Items[j].Value = oldboolvalue;//改回旧的数值
                            }

                            groupStr.Append(newGroupValue);
                            triaGroup.GroupStrs = oldGroupValue;//改回旧的数值
                            break;
                    }


                }
                catch (Exception ex)
                {
                    break;
                }
            }
            var dataStr = groupStr.ToString();
            dataStr = ReverseD(dataStr);
            result = PublicHelper.StrToByte(dataStr);
            //var random = new Random();
            //var t = random.Next(5, 10);
            //Thread.Sleep(t * 1000);
            return result;
        }


        public static string BinaryAddOne(string binary)
        {
            // 将二进制字符串转换为整数
            int number = Convert.ToInt32(binary, 2);
            // 加1
            number+=1;
            // 将结果转换回二进制字符串
            var str = Convert.ToString(number, 2);
            var result = str.PadLeft(8, '0');
            result = ReverseD(result);
            result=result.PadLeft(16,'0');
            return result;
        }


        public static int ByteToInt(byte b)
        {
            var result = 0;
            try
            {
                string hexString = Convert.ToString(b, 16);
                switch(hexString.ToUpper())
                {
                    case "A":
                    case "B":
                    case "C":
                    case "D":
                    case "E":
                    case "F":
                        result = Convert.ToInt32(hexString, 16);
                        break;
                    default:
                        result = int.Parse(hexString);
                        break;
                }
               
            }
            catch (Exception)
            {
                result = 0;
            }
            return result;
        }
    }
}
